package wt

import (
	"os"
	"sync"

	"gitee.com/AlexWoo/arpc/alog"
	"gitee.com/AlexWoo/arpc/anet"
	"google.golang.org/protobuf/proto"
)

var (
	Testwg       sync.WaitGroup
	TestWTServer *Server
	TestHandlerC *TestWTHandler
	TestHandlerS *TestWTHandler
)

type TestWTHandler struct {
	Wait           chan bool
	Conn           *Connection
	HandleResponse func(*anet.Msg)
	HandleRequest  func(*anet.Msg)
}

func (th *TestWTHandler) OnMsg(c anet.Conn, bts []byte) {
	m := &anet.Msg{}
	proto.Unmarshal(bts, m)

	alog.LogInfo(th.Conn.lctx, "OnMsg: %s", m.Str())
	if m.Code == 0 {
		if th.HandleRequest == nil {
			resp := anet.Response(m, anet.OK, nil)
			bts, _ := proto.Marshal(resp)
			th.Conn.Send(bts)
		} else {
			th.HandleRequest(m)
			th.HandleRequest = nil
			th.Wait <- true
		}
	} else {
		if th.HandleResponse != nil {
			th.HandleResponse(m)
			th.HandleResponse = nil
			th.Wait <- true
		}
	}
}

func NewTestWTHandler(conf *alog.LogConf) {
	alog.NewWsLog(conf)

	TestHandlerC = &TestWTHandler{
		Wait: make(chan bool, 1),
	}
}

func NewWTServer(addr string, path string) {
	if TestWTServer != nil {
		return
	}

	os.Mkdir("logs", 0700)
	conf := &ServerConf{
		Addr:     addr,
		CertFile: "certs/arpc.crt",
		CertKey:  "certs/arpc.key",
		Log: alog.LogConf{
			LogLevel: "info",
			LogFile:  "logs/ws.log",
		},
	}

	TestHandlerS = &TestWTHandler{
		Wait: make(chan bool, 1),
	}

	TestWTServer = NewServer(conf)
	TestWTServer.RegisteHandler(path,
		func(c *Connection) anet.Handler {
			TestHandlerS.Conn = c
			return TestHandlerS
		})

	TestWTServer.Run(&Testwg)
}
